#include <stdlib.h>
#include <stdio.h>

typedef struct ListNode
{
    int val;
    struct ListNode *next;
} ListNode;

// 创建新节点的辅助函数
ListNode *createNode(int val)
{
    ListNode *node = (ListNode *)malloc(sizeof(ListNode));
    node->val = val;
    node->next = NULL;
    return node;
}

// 添加节点的辅助函数
void addNode(ListNode **current, int val)
{
    (*current)->next = createNode(val);
    (*current) = (*current)->next;
}

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
    ListNode *head = createNode(0);
    ListNode *p = head;
    int carry = 0;
    while (l1 != NULL || l2 != NULL)
    {
        int sum = carry;
        if (l1 != NULL)
        {
            sum += l1->val;
            l1 = l1->next;
        }
        if (l2 != NULL)
        {
            sum += l2->val;
            l2 = l2->next;
        }
        carry = sum / 10;
        p->next = createNode(sum % 10);
        p = p->next;
    }
    return head;
}

#include <stdarg.h>

void freeLists(int count, ...)
{
    va_list args;
    va_start(args, 0);

    ListNode *head;
    for (size_t i = 0; i < count; i++)
    {
        head = va_arg(args, ListNode *);
        while (head != NULL)
        {
            ListNode *temp = head;
            head = head->next;
            free(temp);
        }
    }
    va_end(args);
}

int main(int argc, char const *argv[])
{
    ListNode *l1 = createNode(2);
    ListNode *tail = l1;
    addNode(&tail, 4);
    addNode(&tail, 3);

    ListNode *l2 = createNode(5);
    tail = l2;
    addNode(&tail, 6);
    addNode(&tail, 4);

    ListNode *head = addTwoNumbers(l1, l2);
    freeLists(2, l1, l2); // 释放l1和l2的内存
    ListNode *result = head->next;
    while (result != NULL)
    {
        printf("%d ", result->val);
        result = result->next;
    }
    freeLists(1, head); // 释放head的内存 栈释放悬空指针
    printf("\n");

    return 0;
}
